package com.cssl.utils;

import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebListener
public class MyListener implements ServletContextListener, HttpSessionListener {

    @Autowired
    private LoginUtils loginUtils;
    private ServletContext application;

    /**
     * @se session创建时触发
     */
    public void sessionCreated(HttpSessionEvent se)  {

        HttpSession session = se.getSession();
        System.out.println("session创建："+session.getId());
        session.setMaxInactiveInterval(600);
    }

    /**
     * @se session销毁的时候触发
     */
    public void sessionDestroyed(HttpSessionEvent se)  {
        HttpSession session = se.getSession();
        String username = (String)session.getAttribute("user");
        //从map里面移除session
        loginUtils.delsession(username);
        List<String> users = (List<String>)application.getAttribute("user");
        if(users.contains(username)) {
            users.remove(username);
        }
    }

    /**
     * @se application创建时触发
     */
    public void contextInitialized(ServletContextEvent sce)  {
        System.out.println("application创建");
        this.application = sce.getServletContext();
    }

    /**
     * @se application销毁时触发
     */
    public void contextDestroyed(ServletContextEvent sce)  {
        System.out.println("application销毁");
    }

}
